package MyTimer;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

public class MyTimer {
    private BlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();

    public MyTimer() {
        Thread t1 = new Thread(() -> {
             while(true) {
                 try {
                     MyTask task = queue.take();
                     if(System.currentTimeMillis() >= task.getTime()) {
                         task.getRunnable().run();
                     }
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
             }
        });
    }


    /**
     * 添加任务的方法
     * @param runnable
     * @param delay
     * @throws InterruptedException
     */
    public void schedule(Runnable runnable, long delay) throws InterruptedException {
        //构建一个task，用于传入队列
        MyTask task = new MyTask(runnable,delay);

        queue.put(task);
    }
}
